import router from '@/router'
import { getToken, removeToken } from './utils/token'
import { ElMessage } from 'element-plus'
import useUserStore from './stores/user/user'
import pinia from './stores'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false }) // 进度条配置 取消加载圈

const userStore = useUserStore(pinia) // 用户信息store
const sensitive = ['/login'] // 无需登录的路由路径
const will: string[] = [] // 未登录时需要跳转的路由路径

router.beforeEach(async (to: any, from: any, next: any) => {
  NProgress.start()
  const token = getToken()
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const hasLogin = !!userStore.userInfo?.name
      if (hasLogin) {
        console.log('已登录', hasLogin)
        next()
      } else {
        try {
          const res = await userStore.getUserInfo()
          console.log('获取用户信息', res)
          if (res.code !== 20000) throw new Error('获取用户信息失败')
          next(to)
        } catch (error) {
          ElMessage({ message: '登录已失效,请重新登录', type: 'warning' })
          removeToken()
          will.push(to.path)
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    if (sensitive.includes(to.path)) {
      next()
    } else if (will.indexOf(to.path) === -1) {
      ElMessage({ message: '请先登录', type: 'warning' })
      next(`/login?redirect=${to.path}`)
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach((to, from, next) => {
  NProgress.done()
})
